package com.shangjinrong.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.shangjinrong.domain.Dict;
import com.shangjinrong.domain.dto.ExcelDictDto;
import com.shangjinrong.excption.BusinessException;
import com.shangjinrong.result.R;
import com.shangjinrong.result.ResponseEnum;
import com.shangjinrong.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Naruto
 */
@RestController
@RequestMapping("admin/dict")
@Slf4j
@CrossOrigin
public class AdminDictController {

    @Autowired
    DictService dictService;


    /**
     * 导入数据字典，excel表格
     *
     * @param file excel文件
     * @return response信息
     */
    @PostMapping("import")
    public R batchImport(@RequestParam("file") MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            dictService.importData(inputStream);

            return R.ok().message("数据字典批量导入成功");
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }
    }

    /**
     * 数据字典导出
     *
     * @param response
     */
    @GetMapping("export")
    public void download(HttpServletResponse response) {


        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = null;
            fileName = URLEncoder.encode("myDict", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExcelDictDto.class).sheet("数据字典").doWrite(dictService.listDictData());
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(ResponseEnum.EXPORT_DATA_ERROR, e);
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.EXPORT_DATA_ERROR, e);
        }
    }

    /**
     * @param parentId 上级id
     * @return
     */
    @GetMapping("listByParentId/{parentId}")
    public R listByParentId(@PathVariable String parentId) {
        List<Dict> dictList = dictService.listByParentId(parentId);
        return R.ok().data("list", dictList);
    }

}
